package com.kdg.snowflake;

import java.util.HashSet;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by kong on 2018/5/24.
 */
public class SnowFlakeTest {
    /*public static void main(String[] args) {
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
        for (int i = 0; i < 1000; i++) {
            long id = idWorker.nextId();
            System.out.println(Long.toBinaryString(id));
            System.out.println(id);
        }
    }*/

    public static HashSet<Long> idSet = new HashSet<>();

    static class SnowFlakeRunnable implements Runnable{

        private SnowflakeIdWorker snowflakeIdWorker;

        public SnowFlakeRunnable(SnowflakeIdWorker snowflakeIdWorker) {
            this.snowflakeIdWorker = snowflakeIdWorker;
        }

        @Override
        public void run() {
            if(this.snowflakeIdWorker != null){
                Long id = snowflakeIdWorker.nextId();
                System.out.println(id);
//                synchronized (SnowflakeIdWorkerTest.class) {
                if (!idSet.add(id)) {
                    System.err.println("存在重复id:" + id);
                }
//                }
            }
        }
    }

    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1000, 1000,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(0,0);
        SnowFlakeRunnable snowFlakeRunnable = new SnowFlakeRunnable(snowflakeIdWorker);
        for(int i=0;i<1000;i++){
            threadPoolExecutor.execute(snowFlakeRunnable);
        }

    }

}
